package com.feature50.makeover.utils;

import com.feature50.makeover.filthy.GraphicsUtilities;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;

public class ImageUtils {
    private static final Logger logger = Logger.getLogger(ImageUtils.class);

    /**
     * Uses ImageIO lib to load an image and return it as an icon. It assumes the image will be in an <code>images/</code>
     * directory in the classpath.
     *
     * @param imageName
     * @return the icon or <code>null</code> if any error occurs
     */
    public static Icon getIcon(String imageName) {
        Image image = getImage(imageName);
        return (image == null) ? null : new ImageIcon(image);
    }

    /**
     * Uses ImageIO lib to load an image and return it. It assumes the image will be in an <code>images/</code>
     * directory in the classpath.
     *
     * @param imageName
     * @return the icon or <code>null</code> if any error occurs
     */
    public static BufferedImage getImage(String imageName) {
        ResourceLoader loader = ResourceLoader.getInstance();

        InputStream in = null;
        try {
            in = loader.getInputStream(ResourceLoader.Type.Image, imageName);
            BufferedImage image = ImageIO.read(in);
            return image;
        } catch (Exception e) {
            logger.error("Couldn't load image " + imageName, e);
            return null;
        } finally {
            try { in.close(); } catch (Exception e) {}
        }
    }

    public static BufferedImage getCompatibleResizedImage(BufferedImage img, int width, int height) {
        BufferedImage ni = GraphicsUtilities.createCompatibleImage(img, width, height);

        Graphics2D g2d = (Graphics2D) ni.getGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.drawImage(img, 0, 0, width, height, null);
        g2d.dispose();

        return ni;
    }

    public static BufferedImage getResizedImage(BufferedImage img, int width, int height) {
        BufferedImage ni = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g2d = (Graphics2D) ni.getGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2d.drawImage(img, 0, 0, width, height, null);
        g2d.dispose();

        return ni;
    }
}